<template>
  <div>
    <a-form-item class="sign" :label="label">
      <a-cascader
        :placeholder="placeholder"
        :options="districtOptions"
        :load-data="loadData"
        @change="onDivisionChange"
        v-decorator="[
          'divisionIds',
          {
            rules: [{ required: true, message: message }]
          }
        ]"
      />
    </a-form-item>
  </div>
</template>

<script>
// 根据id查询下一级数据
function _getOptionsByIds(ids, fn) {
  let options = [];
  return ids
    .slice(0, -1)
    .reduce(
      (p, id) => {
        return p.then(options => {
          const option = options.find(it => it.value === id);
          // option not null
          return fn(id).then(data => (option.children = data));
        });
      },
      fn().then(data => (options = data))
    )
    .then(() => options);
}
export default {
  props: {
    form: {
      type: Object
    },
    // 选中的省市区的id列表,
    divisionIds: {
      type: Array
    },
    // 选中的省市区的name列表
    divisionNames: {
      type: Array
    },
    label: {
      type: String
    },
    placeholder: {
      type: String
    },
    message: {
      type: String
    },
    areaDatas: {
      type: Function,
      default() {
        return () => {
          console.log("获取行政区域");
        };
      }
    }
  },
  data() {
    return {
      districtOptions: []
    };
  },
  created() {
    this.init();
  },
  watch: {
    divisionIds(value) {
      if (value) {
        this.init();
      }
    }
  },
  methods: {
    init() {
      _getOptionsByIds(this.divisionIds, this.areaDatas).then(options => {
        this.districtOptions = options;
        const divisionIds = this.divisionIds;
        this.form.setFieldsValue({ divisionIds });
      });
    },
    // 异步获取行政区域(注：需要运用的时候放开注释)
    loadData(selected) {
      const target = selected[selected.length - 1];
      target.loading = true;
      this.areaDatas(target.value).then(data => {
        target.loading = false;
        if (data.length > 0) {
          target.children = data;
          target.isLeaf = false;
        } else {
          target.isLeaf = true;
        }
        this.districtOptions = [...this.districtOptions];
      });
    },
    // // 选择行政区域
    onDivisionChange(value, selectedOptions) {
      if (value.length != 0) {
        const divisionNames = selectedOptions.map(it => it.label);
        this.$emit("success", divisionNames);
      }
    }
  }
};
</script>

<style></style>
